package com.happyscan138.makefun;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.View.RoundImageView;
import com.happyscan138.makefun.base.http;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;

import cz.msebera.android.httpclient.Header;

import static com.happyscan138.makefun.base.bitmap.getSmallBitmap;
import static com.happyscan138.makefun.base.bitmap.saveMyBitmap;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2016/12/5.
 */

public class Creditor extends AppCompatActivity implements View.OnClickListener{
    private ImageButton back;
    private EditText TextNickName,TextlandSex,TextYear,TextQianming;
    private RoundImageView head;
    private Button buttonSave;
    //声明一个SharedPreferences对象和一个Editor对象
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String accessy_ley;
    private String NickName,Sex,BirthDay,Text;
    private String imagePath;
    private Bitmap bitmap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.creditor);
        initView();
        preferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
        accessy_ley=preferences.getString("UserId","");
        http.params.put("access_key",accessy_ley);
        RequestHandle handler= http.client.post("http://120.25.149.212/wenda/cli-apiaccv1-userinfo.php", http.params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String jsonStr = response.toString();
                try {
                    JSONObject jsonObject=new JSONObject(jsonStr);
                    JSONObject data=jsonObject.getJSONObject("data");
                    String nick_name=data.getString("nick_name");
                    String sex=data.getString("sex");
                    String age=data.getString("age");
                    String sign=data.getString("sign");
                    String imagePath= Urls.base+data.getString("img_path");
                    Picasso.with(getApplicationContext()).load(imagePath).into(head);
//                    new LoadImagesTask(head).execute(imagePath);

                    if(data!=null) {
                        TextNickName.setText(nick_name);
                        TextlandSex.setText(sex);
                        TextYear.setText(age);
                        TextQianming.setText(sign);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                log.e("onSuccess",response.toString());
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                log.e("onFailure",responseString);
            }
        });
        Log.e("access_key",accessy_ley);

    }

    public void initView(){
        TextChange textChange=new TextChange();
        back=(ImageButton)findViewById(R.id.back_UserInfo);
        back.setOnClickListener(this);
        buttonSave=(Button)findViewById(R.id.persioanl_save);
        buttonSave.setOnClickListener(this);
        TextNickName=(EditText)findViewById(R.id.modify_persional_name);
        TextNickName.addTextChangedListener(textChange);
        TextlandSex=(EditText)findViewById(R.id.persional_sex);
        TextlandSex.addTextChangedListener(textChange);
        TextYear=(EditText)findViewById(R.id.persional_birthday);
        TextYear.addTextChangedListener(textChange);
        TextQianming=(EditText)findViewById(R.id.text_qianming);
        TextQianming.addTextChangedListener(textChange);
        head=(RoundImageView)findViewById(R.id.persion_head);
        head.setOnClickListener(this);
        http.client=new AsyncHttpClient();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_UserInfo:
                finish();
                break;
            case R.id.persion_head:
                Intent intent=new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent,0);
                break;
            case R.id.persioanl_save:
                preferences = getSharedPreferences("User", MODE_PRIVATE);
                editor = preferences.edit();
                editor.putString("NickName",NickName);
                editor.putString("sex",Sex);
                editor.putString("age",BirthDay);
                editor.putString("sign",Text);


                http.params.put("access_key",accessy_ley);
                http.params.put("nick_name",NickName);
                http.params.put("sex",Sex);
                http.params.put("age",BirthDay);
                http.params.put("sign",Text);
                http.params.put("email","514878356@qq.com");
                File fileImg = saveMyBitmap(getSmallBitmap(imagePath),imagePath);
                try {
                    http.params.put("file", fileImg);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                log.e("params", http.params.toString());
                RequestHandle handler= http.client.post(Urls.ModifyPersional, http.params,new JsonHttpResponseHandler(){
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr = response.toString();
                        try {
                            JSONObject jsonObject = new JSONObject(jsonStr);
                            String code = jsonObject.getString("code");
                            String msg = jsonObject.getString("msg");
                            int code_int = Integer.valueOf(code).intValue();
                            if (code_int == 1) {
                                Toast.makeText(Creditor.this, msg, Toast.LENGTH_LONG).show();
                               finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        log.e("onSuccess",response.toString());
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                        log.e("onFailure",responseString);
                    }
                });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null) {
            Uri uri = geturi(data);//解决方案
            imagePath=path(uri);
            head.setImageBitmap(getSmallBitmap(path(uri)));

        }
    }
    public Uri geturi(Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[] { MediaStore.Images.ImageColumns._ID },
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }


        return uri;
    }
    private String path(Uri uri ) {

        String path = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, proj, null, null, null);
        log.e("cursor", cursor.toString());
        if (cursor != null) {
            ContentResolver cr = this.getContentResolver();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            path = cursor.getString(column_index);// 图片在的路径
            log.e("path",path);
        }
        return path;

    }




    //EditText的监听器
    private class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            NickName=TextNickName.getText().toString();
            Sex=TextlandSex.getText().toString();
            BirthDay=TextYear.getText().toString();
            Text=TextQianming.getText().toString();
        }
    }
}
